package com.cloudmusic.controller;

import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudmusic.service.DownloadService;

@Controller
@RequestMapping("music/download")
public class DownloadController {
	
	@Autowired
	DownloadService downloadService;

	private Logger log=Logger.getLogger(this.getClass());
	
	//下载歌曲
	@RequestMapping("downloadsong")
	@ResponseBody
	public void downloadOneOfSong(HttpServletRequest request, HttpServletResponse response)throws UnsupportedEncodingException{

		String canshu = request.getParameter("src");
		String sid = canshu.substring(canshu.indexOf("=")+1,canshu.length());
		String realpath = downloadService.findLocallocById(sid);
		String fileName=realpath.substring(realpath.lastIndexOf("\\")+1,realpath.length());
		String	path = realpath;

		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition",
				"attachment;fileName="+new String(fileName.getBytes("gbk"), "iso-8859-1"));
		try {
			File file = new File(path);
			FileInputStream input=new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream(out);
			byte[] buff =new byte[1024*4];
			int index=0;
			while((index= input.read(buff))!= -1){
				bos.write(buff);
			}
			bos.flush();
			log.info("下载文件成功");
			out.close();
			bos.close();
			input.close();
		} catch (Exception e) {
			log.error("下载文件失败", e);
		}



    }
}
